<?php
declare (strict_types = 1);

namespace app\common\command;

use app\common\model\shop\OrderInfoModel;
use app\common\model\shop\OrderModel;
use app\common\model\shop\ozon\OzonGoodsSkuModel;
use app\common\model\shop\PlatformModel;
use app\common\model\shop\self\SelfGoodsSkuModel;
use app\common\model\shop\ShopsModel;
use app\common\service\CrmebService;
use app\common\service\shop\Ozon;
use DateTime;
use DateTimeZone;
use Exception;
use think\admin\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Db;

/**
 * OrderPullCommand
 * @Description
 * @author wangqinghui
 * @date 2024-11-14 10:49
 */
class OrderPullCommand extends Command
{
    /**
     * 配置命令
     * @Description
     * @author wangqinghui
     * @date 2024-11-14 10:50
     * @return void
     */
    protected function configure()
    {
        // 指令配置
        $this->setName('orderpull')->addArgument('platform', Argument::OPTIONAL, "The name of the shop platform", '')
            ->addArgument('shop', Argument::OPTIONAL, "query shopId eg 1,2...", '')->addArgument('start', Argument::OPTIONAL, "query start time", '')
            ->addArgument('end', Argument::OPTIONAL, "query end time", '')
            ->setDescription('Pull Order command');
    }

    /**
     * 执行命令
     * @param \think\console\Input $input
     * @param \think\console\Output $output
     * @Description
     * @author wangqinghui
     * @date 2024-11-14 10:55
     * @return void
     */
    protected function execute(Input $input, Output $output)
    {
        $platform = trim($input->getArgument('platform'));
        $shop_ids   = trim($input->getArgument('shop'));
        $start_time = trim($input->getArgument('start'));
        $end_time   = trim($input->getArgument('end'));

        $this->setQueueProgress(date('Y-m-d H:i:s').' order pull platform:' . $platform . ' start!');
        // 获取平台是否存在
        $map = [
            ['code',        '=',    $platform],
            ['status',      '=',    1]
        ];
        $platform_info = PlatformModel::mk()->where($map)->find();
        if(empty($platform_info)){
            $this->setQueueError('platform: ' . $platform . ' not exists!');
        }

        // 获取平台下店铺
        $platform_id = $platform_info['id'] ?? 0;
        $map = [
            ['platform_id', '=',    $platform_id],
            ['is_deleted',  '=',    0],
            ['status',      '=',    1]
        ];
        if(!empty($shop_ids)){
            $map[] = ['id', 'in', $shop_ids];
        }
        $shop_list = ShopsModel::mk()->where($map)->select()->toArray();
        if(empty($shop_list)){
            $this->setQueueError('platform: ' . $platform . ' shop not exists!');
        }

        $start_time = !empty($start_time) ? $start_time : date('Y-m-d 00:00:00',strtotime('-31 day'));
        $end_time   = !empty($end_time) ? $end_time : date('Y-m-d 23:59:59');

        // 获取平台下订单列表
        $this->getOrderList($platform, $shop_list, $start_time, $end_time);

        $this->setQueueSuccess('platform: ' . $platform . ' 订单拉取成功!');
    }

    /**
     * 获取平台店铺信息
     * @param string $platform_code
     * @param array $shop_data
     * @param string $start_time
     * @param string $end_time
     * @Description
     * @author wangqinghui
     * @date 2024-11-15 11:16
     * @return boolean
     */
    protected function getOrderList(string $platform_code, array $shop_data, string $start_time, string $end_time): bool
    {
        if(empty($platform_code)){
            $this->setQueueProgress('platform param not exists!');
            return false;
        }
        if(empty($shop_data) || !is_array($shop_data)){
            $this->setQueueProgress('shop param not exists!');
            return false;
        }
        
        // 实例化平台接口服务
        switch (strtolower($platform_code)) {
            case PlatformModel::OZON_CODE:
                // 获取ozon订单
                $startTime = (new DateTime($start_time, new DateTimeZone(date_default_timezone_get())))->format(DATE_ATOM);
                $endTime = (new DateTime($end_time, new DateTimeZone(date_default_timezone_get())))->format(DATE_ATOM);
                $this->getOzonOrderList($shop_data, $startTime, $endTime);
                break;
            case PlatformModel::SELF_CODE:
                // 获取自有商城订单
                $startTime = date('Y/m/d 00:00:00', strtotime($start_time));
                $endTime = date('Y/m/d 23:59:59', strtotime($end_time));
                $this->getSelfOrderList($shop_data, $startTime, $endTime);
                break;
            default:
                $this->setQueueProgress('platform not support!');
                break;
        }
        return true;
    }

    /**
     * 获取ozon列表
     * @param array $shop_data
     * @param string $start_time
     * @param string $end_time
     * @Description
     * @author wangqinghui
     * @date 2024-11-15 09:51
     * @return void
     */
    protected function getOzonOrderList(array $shop_data, string $start_time, string $end_time)
    {
        $limit = 100;
        foreach ($shop_data as $shop_info) {
            $this->setQueueProgress('platform: ozon, shop: ' . $shop_info['name'] . ' start!');
            try {
                $config = [
                    'client_id'     => $shop_info['client_id'] ?? '',
                    'api_key'       => $shop_info['api_key'] ?? '',
                ];
                $ozon_api = new Ozon($config);
                $filter = [
                    'since'  => $start_time,
                    'to'    => $end_time,
                    // 'last_changed_status_date' => [
                    //     'from'  =>  $start_time,
                    //     'to'    =>  $end_time
                    // ],
                ];
                $offset = 1;
                while (true) {
                    // 拉取订单数据
                    $order_result = $ozon_api->getOrderList($filter, $limit, $offset);
                    if(empty($order_result['code']) || $order_result['code'] != 1){
                        $this->setQueueProgress('platform: ozon, shop: ' . $shop_info['name'] . ' api error:'.$ozon_api->getErr());
                        break;
                    }

                    $order_list = $order_result['data'] ?? [];
                    // 没有获取数据
                    if(empty($order_list)){
                        $this->setQueueProgress('platform: ozon, shop: ' . $shop_info['name'] . ' no data!');
                        break;
                    }
                    
                    $list = $order_list['postings'] ?? [];
                    $order_ids = array_column($list, 'posting_number');
                    // 获取订单是否存在
                    $map = [
                        ['order_no', 'in', $order_ids],
                        ['platform_id', '=', $shop_info['platform_id']],
                        ['shop_id',     '=', $shop_info['id']],
                        ['account_id',  '=', $shop_info['account_id']]
                    ];
                    $old_data_list = OrderModel::mk()->where($map)->column('id', 'order_no');
                    if(!empty($list)){
                        foreach ($list as $key => $value) {
                            // 获取包裹单详情
                            $order_pack_info = $ozon_api->getOrderInfo($value['posting_number']);
                            if(empty($order_pack_info['code']) || $order_pack_info['code'] != 1){
                                $this->setQueueProgress('platform: ozon, shop: ' . $shop_info['name'] . ' order_no:'.$value['posting_number'].' get order detail api error:'.$ozon_api->getErr());
                                continue;
                            }

                            $pack_info = $order_pack_info['data'] ?? [];
                            if(empty($pack_info)){
                                $this->setQueueProgress('platform: ozon, shop: ' . $shop_info['name'] . ' order_no:'.$value['posting_number'].' get order detail empty');
                                continue;
                            }
                            // 启动事务
                            Db::startTrans();
                            try {
                                // $customer = $value['customer'] ?? [];
                                $customer = $pack_info['customer'] ?? [];
                                $total_num = $total_price = $total_pay_price = $total_shipping_price = $total_discount_price = $total_refund_price = 0;
                                $order_currency = '';
                                $add_data = [
                                    'platform_id'   =>  $shop_info['platform_id'] ?? 0,// 电商平台
                                    'shop_id'       =>  $shop_info['id'] ?? 0,// 店铺ID
                                    // 'order_no'      =>  $value['posting_number'] ?? '',// 订单号
                                    // 'order_number'  =>  $value['order_number'] ?? '',// 订单编号
                                    'order_no'      =>  $pack_info['posting_number'] ?? '',// 订单号
                                    'order_number'  =>  $pack_info['order_number'] ?? '',// 订单编号
                                    'account_id'    =>  $shop_info['account_id'] ?? 0,// 公司
                                    'goods_num'     =>  $total_num, // 商品总数量
                                    'total_price'   =>  $total_price,// 订单金额
                                    // 'buy_user'      =>  !empty($value['addressee']['name']) ? $value['addressee']['name'] : '',// 买家
                                    // 'buy_mobile'    =>  !empty($value['addressee']['phone']) ? $value['addressee']['phone'] : '',// 买家电话
                                    'buy_user'      =>  !empty($pack_info['addressee']['name']) ? $pack_info['addressee']['name'] : '',// 买家
                                    'buy_mobile'    =>  !empty($pack_info['addressee']['phone']) ? $pack_info['addressee']['phone'] : '',// 买家电话
                                    'pay_money'     =>  $total_pay_price,// 支付金额
                                    'freight_money' =>  $total_shipping_price,// 运费
                                    'discount_money'=>  $total_discount_price,// 优惠金额
                                    'refund_money'  =>  $total_refund_price,// 退款金额
                                    'money_unit'    =>  $order_currency,// 货币单位
                                    'user_name'     =>  $customer['name'] ?? '',// 收件人姓名
                                    'user_mobile'   =>  $customer['phone'] ?? '',// 收件人电话
                                    'status_msg'    =>  $value['status'] ?? '',// 订单状态
                                    // 'country'       =>  !empty($customer['address']['country']) ? $customer['address']['country'] : '',// 收货国家
                                    // 'user_city'     =>  !empty($customer['address']['city']) ? $customer['address']['city'] : '',// 城市
                                    // 'user_region'   =>  !empty($customer['address']['region']) ? $customer['address']['region'] : '',// 省/州
                                    // 'user_district' =>  !empty($customer['address']['district']) ? $customer['address']['district'] : '',// 区/县
                                    // 'user_address'  =>  !empty($customer['address']['address_tail']) ? $customer['address']['address_tail'] : '',// 详细地址
                                    // 'zip_code'      =>  !empty($customer['address']['zip_code']) ? $customer['address']['zip_code'] : '',//邮编
                                    // 'pay_way'       =>  $value['analytics_data']['payment_type_group_name'] ?? '',// 支付方式
                                    'country'       =>  !empty($customer['address']['country']) ? $customer['address']['country'] : '',// 收货国家
                                    'user_city'     =>  !empty($customer['address']['city']) ? $customer['address']['city'] : '',// 城市
                                    'user_region'   =>  !empty($customer['address']['region']) ? $customer['address']['region'] : '',// 省/州
                                    'user_district' =>  !empty($customer['address']['district']) ? $customer['address']['district'] : '',// 区/县
                                    'user_address'  =>  !empty($customer['address']['address_tail']) ? $customer['address']['address_tail'] : '',// 详细地址
                                    'zip_code'      =>  !empty($customer['address']['zip_code']) ? $customer['address']['zip_code'] : '',//邮编
                                    // 'pay_way'       =>  $value['analytics_data']['payment_type_group_name'] ?? '',// 支付方式
                                    // 'express_number'=>  $value['tracking_number'] ?? '',// 快递单号
                                    'pay_way'       =>  $pack_info['analytics_data']['payment_type_group_name'] ?? '',// 支付方式
                                    'express_number'=>  $pack_info['tracking_number'] ?? '',// 快递单号
                                    // 'express_channel'  =>  !empty($value['tpl_integration_type']) ? $value['tpl_integration_type'] : '',// 快递渠道
                                    // 'cancel_reason' =>  !empty($value['cancellation']['cancel_reason']) ? $value['cancellation']['cancel_reason'] : '',// 取消原因
                                    // 'order_time'    =>  !empty($value['in_process_at']) ? date('Y-m-d H:i:s', strtotime($value['in_process_at'])) : null,// 下单时间
                                    'express_channel'  =>  !empty($pack_info['tpl_integration_type']) ? $pack_info['tpl_integration_type'] : '',// 快递渠道
                                    'cancel_reason' =>  !empty($pack_info['cancellation']['cancel_reason']) ? $pack_info['cancellation']['cancel_reason'] : '',// 取消原因
                                    'order_time'    =>  !empty($pack_info['in_process_at']) ? date('Y-m-d H:i:s', strtotime($pack_info['in_process_at'])) : null,// 下单时间
                                    'status'        =>  $this->_getOzonOrderStatus($pack_info['status'] ?? ''),// 订单状态
                                    // 'delivery_time' =>  !empty($value['delivering_date']) ? date('Y-m-d H:i:s', strtotime($value['delivering_date'])) : null,// 发货时间
                                    // 'order_id'      =>  $value['order_id'] ?? 0,// 订单编号
                                    // 'shipment_deadline_time'    =>  !empty($value['shipment_date']) ? date('Y-m-d H:i:s', strtotime($value['shipment_date'])) : null,// 截止发货时间
                                    // 'express_compay'    =>  !empty($value['delivery_method']['tpl_provider']) ? $value['delivery_method']['tpl_provider'] : '',// 快递公司
                                    'delivery_time' =>  !empty($pack_info['delivering_date']) ? date('Y-m-d H:i:s', strtotime($pack_info['delivering_date'])) : null,// 发货时间
                                    'order_id'      =>  $pack_info['order_id'] ?? 0,// 订单编号
                                    'shipment_deadline_time'    =>  !empty($pack_info['shipment_date']) ? date('Y-m-d H:i:s', strtotime($pack_info['shipment_date'])) : null,// 截止发货时间
                                    'express_compay'    =>  !empty($pack_info['delivery_method']['tpl_provider']) ? $pack_info['delivery_method']['tpl_provider'] : '',// 快递公司
                                ];

                                if(isset($old_data_list[$pack_info['posting_number']])){ // 更新订单信息
                                    $order_id = $old_data_list[$pack_info['posting_number']];
                                    $count = OrderModel::mk()->where('id', $order_id)->update($add_data);
                                }else{// 添加商品信息
                                    $order_id = OrderModel::mk()->insertGetId($add_data);
                                }

                                // 获取商品信息
                                $goods_list = $pack_info['products'] ?? [];
                                $sku_list = !empty($pack_info['financial_data']['products']) ? $pack_info['financial_data']['products'] : [];
                                $add_order_goods = [];
                                // 获取平台sku信息
                                $offer_ids = array_column($goods_list, 'offer_id');
                                $sku_data = [];
                                if(!empty($offer_ids)){
                                    $map = [
                                        ['goods_nu', 'in', $offer_ids],
                                    ];
                                    $sku_data = OzonGoodsSkuModel::mk()->where($map)->column('id,sku_code,goods_id,goods_nu', 'goods_nu');
                                }
                                if(!empty($sku_list)){ 
                                    // 获取已同步的订单明细
                                    $map = [
                                        ['order_id',   '=', $order_id],
                                    ];
                                    $old_order_detail_data = OrderInfoModel::mk()->where($map)->column('id', 'sku_id');
                                    foreach ($sku_list as $sku_key => $sku_value) {
                                        $order_currency = $sku_value['currency_code'] ?? '';// 订单货币单位
                                        $product_currency = !empty($goods_list[$sku_key]['currency_code']) ? $goods_list[$sku_key]['currency_code'] : '';// 商品货币单位
                                        $goods_nu = !empty($goods_list[$sku_key]['offer_id']) ? $goods_list[$sku_key]['offer_id'] : '';// 本地sku货号
                                        $temp = [
                                            'order_id'      =>  $order_id ?? 0,// 订单ID
                                            'goods_nu'     =>  $goods_nu,//skuID
                                            'goods_id'      =>  !empty($sku_data[$goods_nu]['goods_id']) ? $sku_data[$goods_nu]['goods_id'] : 0,// 商品ID
                                            'sku_id'        =>  $sku_value['product_id'] ?? 0,// ozon平台sku
                                            'collect_sku'  =>  !empty($sku_data[$goods_nu]['sku_code']) ? $sku_data[$goods_nu]['sku_code'] : '',// 原始sku
                                            'goods_name'    =>  !empty($goods_list[$sku_key]['name']) ? $goods_list[$sku_key]['name'] : '',// 商品名称
                                            'num'           =>  $sku_value['quantity'] ?? 0,// 商品数量
                                            'price'         =>  $sku_value['price'] ?? 0,// 商品单价
                                            'sell_price'    =>  $sku_value['old_price'] ?? 0,// 销售价
                                            'money_unit'    =>  $product_currency,// 货币单位
                                        ];
                                        // 更新明细数据
                                        if(!empty($old_order_detail_data[$sku_value['product_id']])){
                                            $edit_id = $old_order_detail_data[$sku_value['product_id']];
                                            $count = OrderInfoModel::mk()->where('id', $edit_id)->update($temp);
                                        }else{
                                            $add_order_goods[] = $temp;
                                        }
                                        // 总数量
                                        $total_num += ($sku_value['quantity'] ?? 0);
                                        // 总价格
                                        $total_price += round(($sku_value['price'] * $sku_value['quantity']), 4);
                                        // 总支付金额
                                        $total_pay_price += ($sku_value['payout'] ?? 0);
                                        // // 总折扣价
                                        // $total_discount_price += ($sku_value['total_discount_value'] ?? 0);
                                    }
                                    // 添加订单明细
                                    if(!empty($add_order_goods)){
                                        OrderInfoModel::mk()->insertAll($add_order_goods);
                                    }
                                }

                                // 获取运费信息
                                // if(!empty($pack_info['tariffication'])){
                                //     $total_shipping_price = array_sum(array_column($value['tariffication'], 'current_tariff_charge'));
                                // }
                                $total_shipping_price = !empty($pack_info['delivery_price']) ? $pack_info['delivery_price'] : '';
                                
                                // 更新订单数据
                                $update_order = [
                                    'goods_num'     =>  $total_num,
                                    'total_price'   =>  $total_price,
                                    'pay_money'     =>  $total_pay_price,
                                    'discount_money'=>  $total_discount_price,
                                    'money_unit'    =>  $order_currency,
                                    'freight_money' =>  $total_shipping_price,
                                ];
                                OrderModel::mk()->where('id', $order_id)->update($update_order);
                            } catch (Exception $e) {
                                $this->setQueueProgress('platform: ozon, shop: ' . $shop_info['name'] . ' error:'.$e->getMessage());
                            }
                        }
                    }
                    // 没有下一页数据
                    if(empty($order_list['has_next'])){
                        $this->setQueueProgress('platform: ozon, shop: ' . $shop_info['name'] . ' no next page data!');
                        break;
                    }
                    // 分页
                    $offset += $limit;
                }
                
            } catch (Exception $th) {
                $this->setQueueProgress('platform: ozon, shop: ' . $shop_info['name'] . ' error:'. $th->getMessage());
            }
            $this->setQueueProgress('platform: ozon, shop: ' . $shop_info['name'] . ' end!');
        }
    
    }

    /**
     * 获取订单状态
     * @param string $status_name
     * @Description
     * @author wangqinghui
     * @date 2024-11-15 15:00
     * @return integer
     */
    private function _getOzonOrderStatus(string $status_name) : int
    {
        $status = OrderModel::STATUS_CONFIRM;
        switch ($status_name) {
            case 'awaiting_registration':
            case 'acceptance_in_progress':
            case 'awaiting_approve':
            case 'awaiting_packaging':
            case 'awaiting_deliver':
            case 'awaiting_verification':
                $status = OrderModel::STATUS_WAIT;// 待发货
                break;
            case 'arbitration':
            case 'client_arbitration':
            case 'delivering':
            case 'driver_pickup':
            case 'not_accepted':
            case 'sent_by_seller':
                $status = OrderModel::STATUS_SEND;// 已发货
                break;
            case 'cancelled':
            case 'cancelled_from_split_pending':
                $status = OrderModel::STATUS_CANCEL;// 已取消
                break;
            case 'delivered':
                $status = OrderModel::STATUS_SIGN;// 已签收
                break;
            default:
                break;
        }
        return $status;
    }

    /**
     * 同步制定时间内未发货订单
     * @param array $shop_data
     * @param string $start_time
     * @param string $end_time
     * @Description
     * @author wangqinghui
     * @date 2025-01-17 16:16
     * @return void
     */
    protected function getSelfOrderList(array $shop_data, string $start_time, string $end_time)
    {
        $limit = 100;
        foreach ($shop_data as $shop_info) {
            $this->setQueueProgress('platform: 自有平台, shop: ' . $shop_info['name'] . ' start!');
            $config = [
                'client_id'     => $shop_info['client_id'] ?? '',
                'api_key'       => $shop_info['api_key'] ?? '',
                'url'           => $shop_info['url'] ?? '',
            ];
            $crmeb_service = CrmebService::getInstance()->setConfig($config);
            $filter = [
                // 'status'    => 0,//订单状态: 0未发货 1已发货 2已收货 3已完成 -2已退款
                'data'      => $start_time.'-'.$end_time,
            ];
            $page = 1;
            while (true) {
                $order_ret = $crmeb_service->getToken()->getOrderList($filter, $page, $limit);
                if(empty($order_ret['code']) || ($order_ret['code'] != 1)){
                    $this->setQueueProgress('platform: 自有平台, shop: ' . $shop_info['name'] . ' api error:'.$crmeb_service->getError());
                    break;
                }
                $order_list = !empty($order_ret['data']['list']) ? $order_ret['data']['list'] : [];
                if(empty($order_list)){
                    $this->setQueueProgress('platform: 自有平台, shop: ' . $shop_info['name'] . ' no data!');
                    break;
                }
                $order_id_arr = array_column($order_list, 'order_id');
                $old_data_list = [];
                if(!empty($order_id_arr)){
                    // 获取订单是否存在
                    $map = [
                        ['order_no', 'in', $order_id_arr],
                        ['platform_id', '=', $shop_info['platform_id']],
                        ['shop_id',     '=', $shop_info['id']],
                        ['account_id',  '=', $shop_info['account_id']]
                    ];
                    $old_data_list = OrderModel::mk()->where($map)->column('id', 'order_no');
                }
                
                foreach ($order_list as $key => $order_info) {
                    // 开启事务
                    Db::startTrans();
                    try {
                        $order_data = [
                            'platform_id'   => $shop_info['platform_id'],
                            'shop_id'       => $shop_info['id'],
                            'account_id'    => $shop_info['account_id'],
                            'order_no'      => $order_info['order_id'],
                            'order_id'      => $order_info['id'],
                            'goods_num'       => $order_info['total_num'],
                            'total_price'   =>  $order_info['total_price'],
                            'buy_user'      => $order_info['subscriber_name'],
                            'buy_mobile'    => $order_info['subscriber_phone'],
                            'pay_money'     =>  $order_info['pay_price'],
                            'freight_money' =>  $order_info['total_postage'],
                            'discount_money'    =>  $order_info['deduction_price'],
                            'money_unit'  =>  'CNY',
                            'user_name' =>  $order_info['real_name'],
                            'user_mobile'   =>  $order_info['user_phone'],
                            'user_address'   =>  $order_info['user_address'],
                            'status'    =>  $this->_getSelfOrderStatus($order_info['status'], $order_info['paid']),
                            'status_msg'    =>  $order_info['status'],
                            'pay_way'       =>  $order_info['pay_type_name'],
                            'express_number'    =>  $order_info['delivery_id'],
                            'express_compay'    =>  $order_info['delivery_name'],
                            'express_channel'   =>  $order_info['delivery_code'],
                            'order_time'        =>  date('Y-m-d H:i:s', $order_info['add_time']),
                        ];
                        if(!empty($old_data_list[$order_info['order_id']])){
                            $order_id = $old_data_list[$order_info['order_id']];
                            $count = OrderModel::mk()->where('id', '=', $order_id)->update($order_data);
                        }else{
                            $order_id = OrderModel::mk()->insertGetId($order_data);
                        }
                        //订单商品明细
                        $order_sku_list = $order_info['items'] ?? [];
                        if(!empty($order_sku_list)){
                            $bar_code_arr = array_column($order_sku_list, 'bar_code');
                            $order_item_list = $sku_list = [];
                            if(!empty($bar_code_arr)){
                                // 获取订单商品是否存在
                                $map = [
                                    ['order_id',    '=',    $order_id],
                                    ['goods_nu',    'in',   $bar_code_arr],
                                ];
                                $order_item_list = OrderInfoModel::mk()->where($map)->column('id', 'goods_nu');
                                // 获取平台商品
                                $map = [
                                    ['goods_nu', 'in', $bar_code_arr]
                                ];
                                $sku_list = SelfGoodsSkuModel::mk()->where($map)->column('id,goods_nu,goods_id,sku_code,price,sale_price', 'goods_nu');
                            }
                            
                            $add_data = [];
                            foreach($order_sku_list as $key => $sku_info){
                                $bar_code = $sku_info['bar_code'] ?? '';
                                $order_sku_item = [
                                    'order_id'      =>  $order_id,
                                    'goods_nu'      =>  $bar_code,
                                    'goods_id'      =>  !empty($sku_list[$bar_code]['goods_id']) ? $sku_list[$bar_code]['goods_id'] : 0,
                                    'collect_sku'   =>  !empty($sku_list[$bar_code]['sku_code']) ? $sku_list[$bar_code]['sku_code'] : '',
                                    'goods_name'    =>  $sku_info['store_name'] ?? '',
                                    'num'           =>  $sku_info['cart_num'] ?? 0,
                                    'price'         =>  $sku_info['price'] ?? 0,
                                    'sell_price'    =>  !empty($sku_list[$bar_code]['sale_price']) ? $sku_list[$bar_code]['sale_price'] : 0,
                                    'money_unit'    =>  'CNY',
                                ];
                                if(!empty($order_item_list[$bar_code])){
                                    $order_item_id = $order_item_list[$bar_code];
                                    $count = OrderInfoModel::mk()->where('id', '=', $order_item_id)->update($order_sku_item);
                                }else{
                                    $add_data[] = $order_sku_item;
                                }
                            }
                            if(!empty($add_data)){
                                OrderInfoModel::mk()->insertAll($add_data);
                            }
                        }
                        // 提交事务
                        Db::commit();
                    } catch (Exception $th) {
                        // 回滚事务
                        Db::rollback();
                        $this->setQueueProgress('platform: 自有平台, shop: ' . $shop_info['name'] . ' error:'.$th->getMessage());
                    }
                }
                $page ++;
            }
        }
    }

    /**
     * 转换自有商城订单状态
     * @param integer $status_name
     * @param integer $is_paid
     * @Description
     * @author wangqinghui
     * @date 2025-01-18 11:26
     * @return integer
     */
    private function _getSelfOrderStatus(int $status_name, int $is_paid) : int
    {
        $status = OrderModel::STATUS_CONFIRM;
        if($status_name == 0){
            if($is_paid == 1){
                $status = OrderModel::STATUS_WAIT;
            }
        }else{
            $map = [
                1 => OrderModel::STATUS_SEND,
                2 => OrderModel::STATUS_SIGN,
                3 => OrderModel::STATUS_SIGN,
            ];
            if(isset($map[$status_name])){
                $status = $map[$status_name];
            }
        }
        return $status;
    }
}
